<?php

namespace App\Repositories\Acl;

use Prettus\Repository\Eloquent\BaseRepository as Repository;
use App\Events\UpdatePermissionEvent;

class PermissionRepository extends Repository
{

     /**
     * 指定模型名称
     *
     * @return mixed
     */
    function model()
    {
        return 'App\Models\Acl\Permission';
    }

    /**
     * [get description]
     * @return [type] [description]
     */
    public function index($status = null)
    {
        if(isset($status))
        {
            $rows = $this->model->where('status', $status)->orderBy('order', 'ASC')->get();
        }
        else
        {
            $rows = $this->model->orderBy('order', 'ASC')->get();
        }        

        return trees($rows);
    }

    /**
     * 查找指定permission
     *
     * @param $id
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function show($id)
    {
        $permission = $this->find($id); 
        if (!$permission) 
            return responseFail(404);
        return $permission;        
        
    }
    

    /**
     * 更新permission
     *
     * @param $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function renew($request, $id)
    {   
        $control = $request->control.'-'.$request->action;      

        $result = $this->update([
            'title' => $request->title,
            'parent' => $request->parent,
            'action' => $request->action,
            'name' => $control,
            'controller'=>$request->control,
            'subtitle' => $request->subtitle,
            'order' => $request->order,
        ], $id);

        if(!!$result){

            event(new UpdatePermissionEvent($this));

            return responseSuccess('权限更新成功', $result);
        }

        return responseFail(500, '权限更新失败');        
        
    }

    
    public function change($request, $id)
    {
        $row = $this->show($id);
        $status = $row->status;
        
        $result = $this->update([
                'status' => $status==1?0:1,
            ], $id);

        if(!!$result){

            event(new UpdatePermissionEvent($this));

            return responseSuccess('权限状态更新成功', $row);
        }
        
        return responseFail(500,'权限状态更新失败');        
    }

}